<template>
  <a-upload
    name="avatar"
    list-type="picture-card"
    class="avatar-uploader"
    :show-upload-list="false"
    :action="action"
    :before-upload="beforeUpload"
    @change="handleChange"
    method="POST"
    :headers="headers"
    :data="reqData"
  >
    <img v-if="imageUrl" :src="imageUrl" alt="avatar" />
    <div v-else>
      <a-icon :type="loading ? 'loading' : 'plus'" />
      <div class="ant-upload-text">上传图片</div>
    </div>
  </a-upload>
</template>
<script>
import { UPLOADFILE } from '@/services/api';

export default {
  data() {
    return {
      loading: false,
      imageUrl: '',
      action: UPLOADFILE,
      headers: {},
      reqData: {
        type: 4,
      },
    };
  },
  created() {
    this.headers['authorization'] = JSON.parse(
      localStorage.getItem('user')
    ).token;
  },
  methods: {
    handleChange(info) {
      // 上传过程中
      if (info.file.status === 'uploading') {
        this.loading = true;
        return;
      }

      // 上传失败
      if (info.file.status === 'error') {
        this.$message.error(info.file.response.msg);
        this.loading = false;
        return;
      }

      // 上传成功
      this.imageUrl = info.file.response.result.path;
      this.loading = false;
      this.$emit('setLogo', info.file.response.result);
    },
    beforeUpload(file) {
      const isJpgOrPng =
        file.type === 'image/jpeg' || file.type === 'image/png';
      if (!isJpgOrPng) {
        this.$message.error('You can only upload JPG or PNG file!');
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error('Image must smaller than 2MB!');
      }
      return isJpgOrPng && isLt2M;
    },
  },
};
</script>
<style>
.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}

img {
  width: 100%;
}
</style>
